<template>
  <div class="container">
    <!-- 顶部导航栏 -->
    <HeaderNav :active-menu="activeMenu" @menu-select="handleMenuSelect" @user-command="handleUserCommand" />

    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧边栏 -->
      <Sidebar :active-sidebar="activeSidebar" @sidebar-select="handleSidebarSelect" />

      <!-- 右侧内容区域 -->
      <main class="content">
        <div class="content-wrapper">
          <!-- 欢迎横幅 -->
          <WelcomeBanner :profile-complete="profileComplete" :stats="stats" @complete-profile="completeProfile" />
          <!-- 主要内容区域 -->
          <div class="main-dashboard">
            <!-- 轮播图区域 -->
            <DashboardSection title="校园风采">
              <BannerCarousel :banners="activeBanners" @banner-click="handleBannerClick" />
            </DashboardSection>

            <!-- 系统公告 -->
            <DashboardSection title="系统公告">
              <AnnouncementList :announcements="latestAnnouncements" @announcement-click="handleAnnouncementClick"
                @refresh="fetchLatestAnnouncements" />
            </DashboardSection>
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

// 导入API
import { getActiveBanners } from '@/api/banner'
import { getLatestAnnouncements } from '@/api/announcement'

// 导入组件
import HeaderNav from '@/components/layout/HeaderNav.vue'
import Sidebar from '@/components/layout/Sidebar.vue'
import WelcomeBanner from '@/components/home/WelcomeBanner.vue'
import DashboardSection from '@/components/home/DashboardSection.vue'
import BannerCarousel from '@/components/home/BannerCarousel.vue'
import AnnouncementList from '@/components/home/AnnouncementList.vue'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const activeMenu = ref('home')
const activeSidebar = ref('dashboard')
const activeBanners = ref([])
const latestAnnouncements = ref([])
const bannerTimer = ref(null)

// 计算属性
const profileComplete = computed(() => {
  return userStore.isProfileComplete()
})

// 统计数据
const stats = ref({
  totalUsers: '12,458',
  activeToday: '1,234',
  newPosts: '356'
})

// 方法定义
const handleMenuSelect = (index) => {
  activeMenu.value = index
  router.push({ name: index.charAt(0).toUpperCase() + index.slice(1) })
}

const handleSidebarSelect = (index) => {
  activeSidebar.value = index;
  switch (index) {
    case 'chat':
      router.push('/chat');
      break;
    case 'recruitment':
      router.push('/recruitment');
      break;
    case 'lost-found':
      router.push('/lost-and-found')
      break
    case 'second-hand':
      router.push('/second-hand')
      break
    case 'circles':
      router.push('/circle')
      break
    case 'social':
      router.push('/social')
      break
    case 'network':
      router.push('/network')
      break
    case 'recruitment':
      router.push('/recruitment')
      break
    default:
      ElMessage.success(`当前已是在 ${index}页面`)
  }
}

const handleLogout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('userInfo')
  ElMessage.success('已退出登录')
  router.push('/login')
}

const completeProfile = () => {
  router.push('/profile')
}
const getImageUrl = (url) => {
  if (!url) return ''

  // 如果已经是完整URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是相对路径，添加基础URL
  const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:7001'

  // 处理不同格式的路径
  if (url.startsWith('/')) {
    return `${baseUrl}${url}`
  } else {
    return `${baseUrl}/${url}`
  }
}
// 获取轮播图数据
const fetchActiveBanners = async () => {
  try {
    const response = await getActiveBanners()
    if (response.code === 0) {
      activeBanners.value = response.data
    } else {
      console.error('获取轮播图失败:', response.msg)
      // 使用默认数据
      activeBanners.value = [
        {
          banner_id: 1,
          image_url: '/images/banner1.jpg',
          link_url: '/social',
          title: '欢迎加入校友社区',
          display_order: 1
        },
        {
          banner_id: 2,
          image_url: '/images/banner2.jpg',
          link_url: '/circle',
          title: '热门圈子推荐',
          display_order: 2
        },
        {
          banner_id: 3,
          image_url: '/images/banner3.jpg',
          link_url: '/recruitment',
          title: '招聘信息速递',
          display_order: 3
        }
      ]
    }
  } catch (error) {
    console.error('获取轮播图异常:', error)
    // 使用默认数据
    activeBanners.value = [
      {
        banner_id: 1,
        image_url: '/images/banner1.jpg',
        link_url: '/social',
        title: '欢迎加入校友社区',
        display_order: 1
      },
      {
        banner_id: 2,
        image_url: '/images/banner2.jpg',
        link_url: '/circle',
        title: '热门圈子推荐',
        display_order: 2
      }
    ]
  }
}

// 获取最新公告
const fetchLatestAnnouncements = async () => {
  try {
    const response = await getLatestAnnouncements({ limit: 5 })
    if (response.code === 0) {
      latestAnnouncements.value = response.data
    } else {
      console.error('获取公告失败:', response.msg)
      // 使用默认数据
      latestAnnouncements.value = [
        {
          announcement_id: 1,
          title: '系统维护通知',
          content: '系统将于本周六凌晨进行维护升级，预计耗时2小时',
          created_at: new Date().toISOString()
        },
        {
          announcement_id: 2,
          title: '新功能上线',
          content: '校友圈功能已正式上线，欢迎体验',
          created_at: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString()
        }
      ]
    }
  } catch (error) {
    console.error('获取公告异常:', error)
    // 使用默认数据
    latestAnnouncements.value = [
      {
        announcement_id: 1,
        title: '欢迎使用校友平台',
        content: '欢迎各位校友加入我们的社区平台',
        created_at: new Date().toISOString()
      }
    ]
  }
}

// 轮播图点击处理
const handleBannerClick = (banner) => {
  if (banner.link_url) {
    if (banner.link_url.startsWith('http')) {
      window.open(banner.link_url, '_blank')
    } else {
      router.push(banner.link_url)
    }
  }
}

// 公告点击处理
const handleAnnouncementClick = () => {
  ElMessage.success('已阅读公告')
}

onMounted(() => {
  // // 检查用户登录状态
  // if (!userStore.isLoggedIn()) {
  //   router.push('/login')
  //   return
  // }

  // 显示欢迎消息
  const displayName = userStore.getDisplayName()
  ElMessage.success(`欢迎回来，${displayName}！`)

  // 获取数据
  fetchActiveBanners()
  fetchLatestAnnouncements()

  // 设置定时刷新公告（每5分钟）
  bannerTimer.value = setInterval(() => {
    fetchLatestAnnouncements()
  }, 5 * 60 * 1000)
})

onUnmounted(() => {
  if (bannerTimer.value) {
    clearInterval(bannerTimer.value)
  }
})
</script>

<style scoped>
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

/* 主内容区域 */
.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 内容区域样式 */
.content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  margin-left: 280px;
  /* 为固定侧边栏留出空间 */
}

.content-wrapper {
  max-width: 1200px;
  margin: 0 auto;
}

/* 仪表盘区域 */
.main-dashboard {
  display: flex;
  flex-direction: column;
  gap: 24px;
}
</style>